// @Date         2021-12-06
// @Author       Aaron Zhang
// @Description
// @FileName      service.go

package redis

import (
	"errors"
	"fmt"
	"github.com/go-redis/redis/v8"
	"time"
	"zin/config"
)

type ProviderServiceRedis struct {
	Client *redis.Client
}

func NewProviderServiceRedis(params map[string]interface{}) (interface{}, error) {

	if config.Conf.Redis.Host == "" || config.Conf.Redis.Port <= 0 {
		return nil, errors.New("未配置Redis地址，端口号等信息")
	}
	conf := config.Conf.Redis

	writeTimeoutDuration, wdErr := time.ParseDuration(conf.WriteTimeout)
	if wdErr != nil {
		return nil, errors.New("解析Redis配置writeTimeout失败")
	}

	readTimeoutDuration, rdErr := time.ParseDuration(conf.ReadTimeout)
	if rdErr != nil {
		return nil, errors.New("解析Redis配置readTimeout失败")
	}

	dialTimeoutDuration, ddErr := time.ParseDuration(conf.DialTimeout)
	if ddErr != nil {
		return nil, errors.New("解析Redis配置readTimeout失败")
	}

	options := &redis.Options{
		Addr:         fmt.Sprintf("%s:%d", conf.Host, conf.Port),
		DB:           conf.Db,
		WriteTimeout: writeTimeoutDuration,
		ReadTimeout:  readTimeoutDuration,
		DialTimeout:  dialTimeoutDuration,
		MaxRetries:   conf.MaxRetries,
	}

	if conf.Password != "" {
		options.Password = conf.Password
	}

	redisClient := redis.NewClient(options)

	return &ProviderServiceRedis{
		Client: redisClient,
	}, nil
}

func (r *ProviderServiceRedis) GetClient() *redis.Client {
	return r.Client
}
